<template>
    <div>
      <div class="table-operator">
        <a-button type="primary" icon="plus" @click="showAddHomeWork">新建作业</a-button>
      </div>
      <!--table-->
      <s-table
        ref="table"
        size="default"
        rowKey="key"
        :columns="columns"
        :data="loadData"
        :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
        bordered
      >
        <span slot="status" slot-scope="text">
          <template>
            <span class="status-span success" v-if="text === 'E'" style="background-color: #ff0000">错误</span>
            <span class="status-span" v-else-if="text === 'R'" style="background-color: #adff2e">运行中</span>
            <span class="status-span" v-else-if="text === 'F'" style="background-color: #52c41a">完成</span>
            <span class="status-span" v-else style="background-color: #f6a520">等待中</span>
          </template>
        </span>

        <!--<span slot="setting" slot-scope="text">-->
          <!--<template>-->
            <!--<a-tooltip-->
              <!--style="marginTop: 10px"-->
              <!--placement="right"-->
              <!--:getPopupContainer="getPopupContainer"-->
              <!--:autoAdjustOverflow="false"-->
            <!--&gt;-->
                <!--<template slot="title">-->
                  <!--<div>算力值1相当于配置：</div>-->
                  <!--<div style="color: #888">cup: itnerdsss</div>-->
                  <!--<div style="color: #888">内核: itnerdsss</div>-->
                  <!--<div style="color: #888">内存: itnerdsss</div>-->
                <!--</template>-->
            <!--<span style="cursor: pointer">{{text}}T</span>-->
          <!--</a-tooltip>-->
          <!--</template>-->
        <!--</span>-->

        <span slot="action" slot-scope="text, record">
          <template>
            <a @click="confirmPerformHomework(record)" v-if="record._jobState === ''">执行</a>
            <a @click="updateHomework(record)" v-if="record._jobState === 'R' || record._jobState === 'E'">刷新</a>
            <a-divider type="vertical" v-if="record._jobState !== 'F'"/>
            <a @click="confirmDelete(record)">删除</a>
          </template>
        </span>
      </s-table>
      <!--table end-->

      <!--新增作业 modal-->
      <a-modal v-model="addHomeWorkModal.visible" centered destroyOnClose title="新增作业">
        <template slot="footer">
          <a-button key="back" @click="closeHomeWorkModal()">取消</a-button>
          <a-button key="submit" type="primary" :loading="addHomeWorkModal.loading" @click="subaddHomeWorkModal">
            确认
          </a-button>
        </template>
        <a-form :form="form">
          <a-form-item
            v-bind="addHomeWorkModal.formItemLayout"
            label="名称"
          >
            <a-input
              v-decorator="[
          'projuctName',
          { rules: [{ required: true, message: '请输入名称' }] },
        ]"
              placeholder="请输入名称"
            />
          </a-form-item>

          <a-form-item
            v-bind="addHomeWorkModal.formItemLayout"
            label="上传文件"
            :required="true"
            :validate-status = "addHomeWorkModal.isUploadFile"
            :help="addHomeWorkModal.errorText"
          >
            <a-upload
              v-decorator="[
          'upload',
          {
            valuePropName: 'addHomeWorkModal.fileList',
            getValueFromEvent: normFile,
          },
          { rules: [{ required: true, message: '请上传文件' }] },
        ]"
              name="deploymentUpload"
              :fileList="addHomeWorkModal.fileList"
              :action="addHomeWorkModal.postUrl"
              list-type="text"
              :beforeUpload="uploadBeforeUpload"
              @change="deploymentUploadChange"
            >
              <a-button> <a-icon type="upload" /> 选择文件</a-button>
            </a-upload>
          </a-form-item>

          </a-form-item>

        </a-form>
      </a-modal>
      <!--新增作业 modal end-->
    </div>
</template>

<script>
  import { Radar, STable } from '@/components'
  // import { getRoleList, getServiceList } from '@/api/manage'
  import { getHpcHomeWorkList, getHpcSshInfoById, subAllHomework, deleteAllHomework, performAllHomework, updateHomeworkStatus } from '@/api/aihpc'
    export default {
        name: "homeworkComponentInfo",
        data(){
          return {
            form: this.$form.createForm(this),
            addHomeWorkModal: {
              loading: false,
              visible: false,
              hpcItem: {},
              postUrl: '/remote/upload',
              sshIp: '',
              fileList: [],
              isUploadFile: 'success',
              errorText:'',
              hpcId: '',
              pathUrl: '',
              formItemLayout: {
                labelCol: {
                  xs: { span: 24 },
                  sm: { span: 5 },
                },
                wrapperCol: {
                  xs: { span: 24 },
                  sm: { span: 19 },
                },
              }
            },
            appName: '',
            cpuTypeName: '',
            // 表头
            columns: [
              {
                title: '作业编号',
                dataIndex: '_workId'
              },
              {
                title: '作业名称',
                dataIndex: '_name'
              },
              {
                title: '应用',
                dataIndex: 'app',
                // sorter: true,
                // needTotal: true,
                // scopedSlots: { customRender: 'setting' },
                customRender: (text) => this.appName
              },
              {
                  title: '运行用户',
                  dataIndex: '_owner',
                  customRender: (text) => text.replace('@master', '')
                  // sorter: true
              },
              {
                title: '核数',
                dataIndex: '_ncpus',
                // sorter: true
              },
              {
                title: 'CPU规格',
                dataIndex: 'machine',
                // sorter: true
                customRender: (text) => this.cpuTypeName
              },
              {
                title: '内存',
                dataIndex: '_mem',
                // sorter: true
              },
              {
                title: '任务进度',
                dataIndex: 'updatedAtssa',
                // sorter: true
              },
              {
                title: '运行状态',
                dataIndex: '_jobState',
                scopedSlots: { customRender: 'status' }
              },
              {
                title: '提交时间',
                dataIndex: '_timestamp',
                // sorter: true
              },
              {
                title: '运行时长',
                dataIndex: '_walltime',
                // sorter: true
              },
              {
                title: '操作',
                dataIndex: 'action',
                scopedSlots: { customRender: 'action' }
              }
            ],
            tableDatas: {
              data: [],
              pageNo: 1,
              pageSize: 10,
              totalCount: 0,
              totalPage: 0
            },
            // 加载数据方法 必须为 Promise 对象
            loadData: parameter => {
              let that = this;
              let params = {
                _id: that.$route.params.id
              }
              return getHpcHomeWorkList(params)
                .then(res => {
                  let data = res && res.data ? res.data.rows : [];
                  that.tableDatas.data = data.jobs;
                  that.tableDatas.totalCount = data.jobs.length;
                  that.appName = data.app ? data.app._name : '';
                  that.cpuTypeName = data.machine ? data.machine._name : '';
                  return that.tableDatas
                }).catch(err => {
                  that.$message.error("获取作业列表失败")
                  return that.tableDatas
                })
            },
            selectedRowKeys: [],
            selectedRows: [],

            // custom table alert & rowSelection
            options: {
              alert: false,
              rowSelection: {
                selectedRowKeys: [],
                onChange: this.onSelectChange
              }
            }
          }
        },
        components: {
          STable
        },
        mounted () {

        },
        methods:{
          showAddHomeWork: function (items) {
            this.addHomeWorkModal.visible = true;
            this.addHomeWorkModal.hpcItem = items;
          },
          normFile(e) {
            if (Array.isArray(e)) {
              return e;
            }
            return e && e.fileList;
          },
          uploadBeforeUpload: function (file) {
            const zip = file.type === 'application/zip' || file.type === 'application/x-zip' || file.type === 'application/x-zip-compressed';
            if (!zip) {
              this.$message.error('请上传zip格式文件');
            }
            this.addHomeWorkModal.fileList = []
            return zip;
          },
          deploymentUploadChange: function (info) {
            if(info.file.type === 'application/zip' || info.file.type === 'application/x-zip' || info.file.type=== 'application/x-zip-compressed'){
              this.addHomeWorkModal.isShowUpload = false;
              if (info.file.status !== 'uploading') {

              }
              if (info.file.status === 'done') {
                this.$message.success(`上传成功`);
                let data = info && info.file && info.file.response ? info.file.response : ''
                this.addHomeWorkModal.pathUrl = data  ? data.path : ''
              } else if (info.file.status === 'error') {
                this.$message.error(`上传失败`);
              }

            }
            this.addHomeWorkModal.isUploadFile='success'
            this.addHomeWorkModal.errorText=''
            this.addHomeWorkModal.fileList = info.fileList;
          },
          updateHomework: function (data){
              let that = this;
              let params = {
                  _id: data._id
              }
              updateHomeworkStatus(params)
                  .then((res)=>{
                      that.$refs.table.refresh(true)
                      that.$message.success("刷新状态成功")
                  }).catch((err)=>{
                  that.$message.error("刷新状态失败")
              })
          },
          confirmPerformHomework(data) {
            let that = this;
            this.$confirm({
              title: `执行作业`,
              content: `是否确认执行${data._name}？`,
              okText: '确认',
              cancelText: '取消',
              centered: true,
              destroyOnClose: true,
              maskClosable: true,
              onOk() {
                that.performHomework(data);
              },
            });
          },
          performHomework: function (data) {
            let that = this;
            let params = {
              _id: data._id
            }
            performAllHomework(params).then((res)=>{
              that.$refs.table.refresh(true)
              that.$message.success("执行作业成功")
            }).catch((err)=>{
              that.$message.error("执行作业失败")
            })
          },
          confirmDelete(data) {
            let that = this;
            this.$confirm({
              title: `删除作业`,
              content: `是否确认删除${data._name}？`,
              okText: '确认',
              cancelText: '取消',
              centered: true,
              destroyOnClose: true,
              maskClosable: true,
              onOk() {
                that.deleteHomeWork(data);
              },
            });
          },
          deleteHomeWork: function (data) {
            let that = this;
            let params = {
              _id: data._id
            }
            deleteAllHomework(params).then((res)=>{
              that.$refs.table.refresh(true)
              that.$message.success("删除作业成功")
            }).catch((err)=>{
              that.$message.error("删除作业失败")
            })
          },
          closeHomeWorkModal: function () {
            this.addHomeWorkModal.visible =false;
          },
          subaddHomeWorkModal: function (){
            let that = this;
            this.form.validateFields((err, values) => {
              if (!err) {
                if(that.addHomeWorkModal.pathUrl){
                  let params = {
                    _name: values ? values.projuctName : '',
                    _path: that.addHomeWorkModal.pathUrl,
                    _instanceId: that.$route.params.id ? that.$route.params.id : 0
                  };

                  subAllHomework(params)
                    .then((res) => {
                      that.$message.success('新建作业成功');
                      that.addHomeWorkModal.isUploadFile='success'
                      that.addHomeWorkModal.errorText=''
                      that.$refs.table.refresh(true);
                      that.closeHomeWorkModal();
                    }).catch(err => {
                    that.$message.error('新建作业失败');
                    that.closeHomeWorkModal();
                  })
                }else{
                  that.addHomeWorkModal.isUploadFile = 'error'
                  that.addHomeWorkModal.errorText='请上传作业文件'
                  that.$message.error('请上传作业文件');
                }

              }
            })
          },
          getPopupContainer(trigger) {
            return trigger.parentElement;
          },
          onSelectChange: function(selectedRowKeys) {
            this.selectedRowKeys = selectedRowKeys;
          },
        }
    }
</script>

<style lang="less" scoped>
  .status-span{
    padding: 3px 10px;
    border-radius: 15px;
    color: #fff;
    font-size: 12px;
    text-align: center;
    display: inline-block;
  & .success{
      background-color: #52c41a;
    }
  }
  @media (max-width: 575px){
    .status-span{
      padding: 3px 5px;
    }
  }
</style>